// 实现一个基本的计算器来计算一个简单的字符串表达式 s 的值
// 输入：s = " 2-1 + 2 "
// 输出：3
// 可行，但是超时
function calculate(s) {
  s = s.replace(/\s/g, "");
  if (/^\d+$/.test(s)) return s;
  const reg = /(\+|\-)?(\([\d\-\+]+\))/;
  while (reg.test(s)) {
    s = s.replace(reg, function (a, symbol, target) {
      target = target.replace(/^\(/, "").replace(/\)$/, "");
      if (symbol === "-") {
        const nextTarget = replace(target.split(""), [
          { prev: "+", next: "-" },
          { prev: "-", next: "+" }
        ]).join("");
        return symbol + nextTarget;
      } else if (symbol === "+") {
        return symbol + target;
      }
      return target;
    });
  }
  return calc(s);
  function calc(s) {
    s = s.match(/[\+\-]|\d+/g);
    if (s[0] !== "-") {
      s.unshift("+");
    }
    let ret = 0;
    for (let n = 0; n < s.length; n += 2) {
      if (s[n] === "+") {
        ret = ret + Number(s[n + 1]);
      } else {
        ret = ret - Number(s[n + 1]);
      }
    }
    return ret;
  }
  function replace(array, option) {
    return array.map((ele) => {
      const { next } =
        option.find((op) => {
          return op.prev === ele;
        }) || {};
      return next || ele;
    });
  }
}

console.log(calculate("1-2"));
